var toolBarRoadName = "",
    startRoad4Select = "",
    endRoad4Select = "",
    coverProvince = 0,
    coverCity = 0,
    coverArea = 0,
    coverFlag = 0;
var myDate = new Date();
var date = myDate.getFullYear() + "-" +
    myDateFormat(myDate.getMonth() + 1) + "-" +
    myDateFormat(myDate.getDate());
var currentActorId = 3;
var localOrgId = 0;
if (gUserLoginResult.userActors.indexOf("7") >= 0) currentActorId = 7;
if (gUserLoginResult.userActors.indexOf("1") >= 0) currentActorId = 1;

function myDateFormat(s) {
    return s < 10 ? '0' + s : s;
}

var localActorId;
$(function () {
    localActorId = currentActorId;
    localOrgId = gUserLoginResult.orgId;
    gMainDT = $("#mainDataTable").DataTable({
        ajax: {
            url: "../rds_CoverManage/getCover4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTable').DataTable().search(this.value);
                d.actorIds = localActorId;
                d.orgId = localOrgId;
                d.audit = false;
                d.startRoad = startRoad4Select;
                d.endRoad = endRoad4Select;
                d.roadName = toolBarRoadName;
            }
        },
        columns: [{
            data: "coverId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: null,
            targets: 0
        }, {
            data: "coverPhoto",
            render: function (data, type, row) {
                return "<img src='" + data + "' style='width: 50px; height: 40px; cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + data + "\")'>";
            }
        }, {
            data: null,
            render: function (data, type, row) {
                var str = "<button id='showMap' " +
                    "onclick='$.showMap(" + row.coverLongitude + "," + row.coverLatitude + ")' " +
                    "class='btn  btn-primary  btn-xs btn-flat' title='地图位置'>" +
                    "<i class='glyphicon glyphicon-map-marker'></i></button> ";
                str += row.coverProvince + " " + row.coverCity + " " + row.coverArea;
                return str;
            }
        }, {
            data: "coverRoadName"
        }, {
            data: null,
            render: function (data, type, row) {
                return row.coverStartRoad + "——" + row.coverEndRoad;
            }
        }, {
            data: "coverOrgName"
        }, {
            data: "coverCreatorName"
        }, {
            data: "coverInstallTime"
        }, {
            data: "coverId",
            render: function (data, type, row) {
                return "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showInfo(" + JSON.stringify(row) + ")' title='信息查看'>" +
                    "<i class='glyphicon glyphicon-eye-open'></i></button> " +
                    "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showQrcode(" + JSON.stringify(row) + ")' title='二维码'>" +
                    "<i class='glyphicon glyphicon-qrcode'></i></button>";
            }
        }, {
            data: "coverId",
            render: function (data, type, row) {
                var buttonOperation = "";
                if (row.coverIsComplete == 1)
                    buttonOperation += "<button  class='btn  btn-success btn-xs btn-flat' title='已审核'>" +
                        "<i class='fa  fa-check-square-o'></i></button> ";
                else
                    buttonOperation += "<button  class='btn  btn-danger btn-xs btn-flat' title='未审核'>" +
                        "<i class='fa fa-square-o'></i></button> ";

                var buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showUpdateCover(" + JSON.stringify(row) + ")' title='编辑'>" +
                    "<i class='fa fa-edit'></i></button> ";
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonUpdate;

                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showDeleteCover(" + data + ")' title='删除'>" +
                    "<i class='fa fa-minus-square'></i></button>";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;

                return buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-2'l><'#mainToolbar.col-md-10'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' " +
                "data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
                "<span class='caret'></span><span class='sr-only'>切换下拉</span></button>" +
                "<ul class='dropdown-menu'>" +
                "<li>" +
                "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>" +
                "</li>";

            var buttonAdd = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.showAddCover()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonAdd;
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.showDeleteCover(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;

            var html2 = "";
            if(currentActorId == 1)
                html2 += "<select id='orgId4Select' style='max-width: 280px' onchange='$.getCoverStartRoad()' class='form-control'>" + gOrgListHtml +"</select>&nbsp;";
            strToolBar += "</ul></div> " +
                "<div class='input-group-sm' style='display:inline-block'>" + html2 +
                "<input id='toolBarRoadName' onkeyup='$getCoverStartRoad()'  type='text' class='form-control mysize' placeholder='路名'>" +
                "&nbsp;<select   style='width: 80px' onchange='$.getCoverEndRoad()' class='form-control mysize' id='startRoad4Select'>" +
                "<option value=''>起/止</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='endRoad4Select'>" +
                "<option value=''>止/起</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDT()'>" +
                "<i class='fa fa-search'></i></button></div></div>";

            $("#mainToolbar").append(strToolBar);
            $.getCoverStartRoad();
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(1).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    var oTable = $('#mainDataTable').dataTable();
    if (gUserLoginResult.userActors.indexOf('1') > -1) {
        oTable.fnSetColumnVis(5, false);
        oTable.fnSetColumnVis(7, false);
    } else if (gUserLoginResult.userActors.indexOf('7') > -1) {
        oTable.fnSetColumnVis(0, false);
        oTable.fnSetColumnVis(5, false);
        oTable.fnSetColumnVis(7, false);
        oTable.fnSetColumnVis(9, false);
    } else {
        oTable.fnSetColumnVis(6, false);
    }


});

var gActorId = gUserLoginResult.userActors.includes("1") ? 1 : 2;
$.getOrgList = function () {
    var html = "", result = "";
    $.ajax({
        url: "../rds_fault/getOrg4Select",
        type: "post",
        async: false,
        data: {
            actorId: gActorId,
            orgId: gUserLoginResult.orgId
        },
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess) {
                    var jsonData = msg.jsonData;
                    var orglist = "";
                    if (jsonData.length == 0) {
                        firstOrgId = gUserLoginResult.orgId;
                        result = "<option value='" + gUserLoginResult.orgId + "'>" + gUserLoginResult.orgName + "</option>"
                    }
                    else {

                        for (var i in jsonData) {
                            orglist += "," + jsonData[i].orgId;
                            html += "<option value='" + jsonData[i].orgId + "'>" + jsonData[i].orgName + "</option>"
                        }
                        orglist = orglist.substr(1);
                        if (gActorId == 1) {
                            result += "<option value='-2'>全部</option>" +
                                "<option value='-1'>未设置</option>"
                            firstOrgId = -2;
                        }
                        else {
                            firstOrgId = orglist
                            result += "<option value='" + orglist + "'>全部</option>"
                        }
                        result += html;
                    }

                }

            }
        }
    })
    return result;
}

var gOrgListHtml = $.getOrgList();

$.getCoverStartRoad = function () {
    var mOrgId = $("#orgId4Select").val();
    var localOrg = gUserLoginResult.orgId;
    var mActorId = currentActorId;
    if (mActorId != 7) {
        if (mOrgId == -2) {
            mActorId = 1;
        } else if(mOrgId){
            mActorId = 3;
            localOrg = mOrgId;
        }
    }
    $.ajax({
        url: "../rds_CoverManage/getStartRoadByRoadName",
        type: "POST",
        data: {
            "roadName": $("#toolBarRoadName").val(),
            "actorIds": mActorId,
            "orgId": localOrg
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#startRoad4Select").empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#startRoad4Select").append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#startRoad4Select").append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    }
                    else
                        $("#startRoad4Select").append("<option>无</option>");
                } else {
                    $.alert("获取起始道路数据失败", 2);
                }
            }
        }
    })
};

function _debounce(fn, delay) {
    var timer
    return function () {
        var context = this
        var args = arguments
        clearTimeout(timer)
        timer = setTimeout(function () {
            fn.apply(context, args)
        }, delay)
    }
}

var $getCoverStartRoad = _debounce($.getCoverStartRoad, 1000);

$.getCoverEndRoad = function () {
    $.ajax({
        url: "../rds_CoverManage/getEndRoadByStartRoad",
        type: "POST",
        data: {
            "city": "",
            "coverRoadName": $("#toolBarRoadName").val(),
            "startRoad": $("#startRoad4Select").val(),
            "actorIds": gUserLoginResult.userActors,
            "orgId": gUserLoginResult.orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#endRoad4Select").empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#endRoad4Select").append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#endRoad4Select").append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    }
                    else
                        $("#endRoad4Select").append("<option>无</option>");
                } else {
                    $.alert("获取起始道路数据失败", 2);
                }
            }
        }
    })
}

$.Trim = function (str, is_global) {
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g, "");
    if (is_global.toLowerCase() == "g") {
        result = result.replace(/\s/g, "");
    }
    return result;
};

$.fn.searchDT = function () {
    toolBarRoadName = $.Trim($("#toolBarRoadName").val(), "g");
    startRoad4Select = $("#startRoad4Select").val();
    endRoad4Select = $("#endRoad4Select").val();
    localOrgId = $("#orgId4Select").val();
    if (localActorId != 7) {
        if (localOrgId == -2) {
            localActorId = 1;
        } else {
            localActorId = 3;
        }
    }
    if(!localOrgId)
    {
        localOrgId = gUserLoginResult.orgId;
    }
    gMainDT.search($("#searchText").val()).draw();
};

$.checkChange = function () {
    var isChecked = $("#batchCheck").prop('checked');
    $("input:checkbox[id^='checkbox']").prop("checked", isChecked);
};

$.showInfo = function (jsonData) {
    $(".no_act").show();
    $("#defaultFooter").hide();
    $("#specialFooter").show();
    $("#myBtn").attr("onclick", "$.showMap(" + jsonData.coverLongitude + "," + jsonData.coverLatitude + ")");
    $.showUpdateCover(jsonData, 3);
};

$.beDefault = function () {
    $("#myBtn").attr("onclick", "");
    $(".no_act").hide();
    $("#defaultFooter").show();
    $("#specialFooter").hide();
};

$.showMap = function (x, y) {
    X = x;
    Y = y;
    $("#modalMapRoad").hide();
    var url = "management/poleMap.html";
    url += "?x=" + x + "&y=" + y + "&z=1";//通过这种方式传参数
    $("#myMap").attr("src", url);
    $("#modal-map").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

$.showHistory = function (coverId) {
    historyDt = $("#historyDataTable").DataTable({
        ajax: {
            url: "../rds_roadSignManageController/getHistory4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#historyDataTable').DataTable().search(this.value);
                d.equipmentId = coverId;
                d.equipmentType = 9;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: "eventType"
        }, {
            data: "operatingTime"
        }, {
            data: "operatingPerson"
        }],
        dom: "<'row'<'col-md-6'><'#historyTool.col-md-6'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            $("#historyTool").empty();
            var strToolBar = "<div class='input-group input-group-sm'>" +
                "<input type='text' class='form-control' id='datePicker' placeholder='操作时间'>" +
                "<span class='input-group-btn'>" +
                "<button class='btn btn-primary btn-flat' type='button' " +
                "onclick='$(this).searchInfoInHistoryDt()'><i class='fa fa-search'></i>" +
                "</button></span></div>";
            $("#historyTool").append(strToolBar);
            $("#datePicker").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $(this).searchInfoInHistoryDt();
                }
            });
            $('#datePicker').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayBtn: 'linked',
                language: 'zh-CN'
            });
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        destroy: true,
        displayLength: 10,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    $("#historyModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$.fn.searchInfoInHistoryDt = function () {
    var search = $("#datePicker").val().replace(/'/g, '');
    historyDt.search(search).draw();
};

$.showQrcode = function (jsonData) {
    $("#qrcode").empty();
    var qrcode = new QRCode(document.getElementById("qrcode"), {
        width: 200,
        height: 200
    });
    qrcode.makeCode("orgId:" + jsonData.coverOrgId + ",coverId:" + jsonData.coverId);
    $("#qrcodeModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$("#province").change(function () {
    coverProvince = $("#province").val();
    $.getRegion("city", $("#province").val());
    $("#city").val(parseInt($("#province").val()) + 100);
    coverCity = $("#city").val();
    $.getRegion("area", $("#city").val());
    $("#area").val(parseInt($("#city").val()) + 1);
    coverArea = $("#area").val();
});

$("#city").change(function () {
    coverCity = $("#city").val();
    $.getRegion("area", $("#city").val());
    $("#area").val(parseInt($("#city").val()) + 1);
    coverArea = $("#area").val();
});

$("#area").change(function () {
    coverArea = $("#area").val();
});

$.getRegion = function (id, pid) {
    $.ajax({
        url: "../rds_roadSignManageController/getRegion4Select",
        type: 'post',
        async: false,
        dataType: 'json',
        data: {
            'pid': pid
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var provinceData = msg.jsonData;
                    $("#" + id).empty();
                    if (provinceData.length != 0) {
                        provinceDataFlag = 0;
                        for (var i = 0; i < provinceData.length; i++)
                            $("#" + id).append("<option value='" + provinceData[i].regionId + "'>" +
                                provinceData[i].regionName + "</option>");
                    }
                    else {
                        provinceDataFlag = 1;
                        $("#" + id).append("<option value='" + gUserLoginResult.regionId + "'>" +
                            gUserLoginResult.regionName + "</option>");
                    }
                } else {
                    $.alert("获取地区列表失败", 2);
                }
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function () {
            $.alert("系统错误", 2);
        }
    });
};


$.getMainOrgNameAndId = function (orgId) {
    $.ajax({
        url: "../rds_org/getMainOrgNameAndId",
        type: 'post',
        async: false,
        dataType: 'json',
        data: {
            'orgId': orgId
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var orgData = msg.jsonData;
                    $("#coverMainOrgId").empty();
                    if (orgData.length != 0) {
                        orgDataFlag = 0;
                        for (var i = 0; i < orgData.length; i++)
                            $("#coverMainOrgId").append("<option value='" + orgData[i].orgId + "'>" +
                                orgData[i].orgName + "</option>");
                    } else {
                        orgDataFlag = 1;
                        $("#coverMainOrgId").append("<option value='" + gUserLoginResult.orgId + "'>" +
                            gUserLoginResult.orgName + "</option>");
                    }
                } else {
                    $.alert("获取监管单位数据失败", 2);
                }
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function () {
            $.alert("系统错误", 2);
        }
    });
};

$("#myBtn").click(function () {
    $("#modalMapRoad").show();
    $("#startRoad").val($("#coverStartRoad").val());
    $("#endRoad").val($("#coverEndRoad").val());
    var url = "management/roadPoleMap.html";
    var coo = $("#coordinate").val(),
        coordinate,
        type = 1,
        x, y;
    if (coo != "") {
        coordinate = $("#coordinate").val().split(",");
        x = coordinate[0];
        y = coordinate[1];
    } else {
        x = $("#city").find("option:selected").text();
        y = $("#area").find("option:selected").text();
        type = 0;
    }
    url += "?x=" + x + "&y=" + y + "&z=" + type + "";//通过这种方式传参数
    coverArea = $("#area").val();
    $("#myMap").attr("src", url);
    $("#modal-map").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
});

$("#subBtn").click(function () {
    $("#coverStartRoad").val($("#startRoad").val());
    $("#coverEndRoad").val($("#endRoad").val());
    $("#coverRoadName").val(sessionStorage.getItem("roadName"));
    $("#coordinate").val(sessionStorage.getItem("x") + "," + sessionStorage.getItem("y"));
    $('#modal-map').modal("hide");
});

$('#coverInstallTime').datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
    todayBtn: 'linked',
    language: 'zh-CN'
});

$.openUpPic = function () {
    $("#upPictureModal").modal({
        backdrop: 'static',
        keyboard: true,
        show: true
    });
};

$.closeUpPhModal = function () {
    $("#upPictureModal").modal("hide");
    $("#ossfile").empty();
    clearOssData();
};

$.doneUpPhoto = function () {
    var fileInfo = getOssFileInfo();
    var fileUrl = fileInfo[0].fileUrl;
    $("#coverPhotoImg").attr("src", fileUrl);
    $("#coverPhoto").val(fileUrl);
    $.closeUpPhModal();
};

function judgeFileType(suffix) {
    //图片文件
    if (!(suffix == ".jpg" || suffix == ".JPG" || suffix == ".png" || suffix == ".PNG" ||
            suffix == ".jpeg" || suffix == ".JPEG" || suffix == ".gif" || suffix == ".GIF" ||
            suffix == ".bmp" || suffix == ".BMP")) {
        alert("请选择图片文件！");
        return false;
    }
}


$.showAddCover = function () {
    coverFlag = 0;
    $.getRegion("province", 0);
    if (coverProvince == 0)
        $("#province").val(330000);
    else
        $("#province").val(coverProvince);
    $.getRegion("city", $("#province").val());
    if (coverCity == 0)
        $("#city").val(330200);
    else
        $("#city").val(coverCity);
    $.getRegion("area", $("#city").val());
    if (coverArea == 0)
        $("#area").val(330211);
    else
        $("#area").val(coverArea);

    $("#coverInstallTime").val(date);
    $("#coverOrgName").val(gUserLoginResult.orgName);
    $("#coverPhotoImg").attr("src", "../images/default_photo.png");
    $("#coverPeriod").val(1);
    $("#coverServiceLife").val(1);
    $.getMainOrgNameAndId(gUserLoginResult.orgId);
    $("#coverShape").val(0);
    $("#coverMaterial").val(0);
    $("#coverCreatorName").val(gUserLoginResult.userName);
    $("#coverCreatorId").val(gUserLoginResult.userId);
    $("#coverOrgId").val(gUserLoginResult.orgId);
    $("#coverPhoto").val("../images/default_photo.png");

    $("#coverLabel").text("添加窨井信息");
    $("#coverModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$.showUpdateCover = function (jsonData) {
    map_type = (arguments[1]) ? arguments[1] : 1;
    $("#coverLabel").text(map_type == 1 ? "编辑信息" : "信息展示");//展示or编辑

    coverFlag = 1;
    $("#projectNumber").val(jsonData.projectNumber);
    $.getRegion("province", 0);
    $("#province").val(jsonData.coverRegionId.toString().substring(0, 2) + "0000");
    $.getRegion("city", $("#province").val());
    $("#city").val(jsonData.coverRegionId.toString().substring(0, 4) + "00");
    $.getRegion("area", $("#city").val());
    $("#area").val(jsonData.coverRegionId);

    $("#coordinate").val(jsonData.coverLongitude + "," + jsonData.coverLatitude);
    $("#coverRoadName").val(jsonData.coverRoadName);
    $("#coverStartRoad").val(jsonData.coverStartRoad);
    $("#coverEndRoad").val(jsonData.coverEndRoad);
    $("#coverBrand").val(jsonData.coverBrand);
    $("#coverInstallOrg").val(jsonData.coverInstallOrg);
    $("#coverInstallTime").val(jsonData.coverInstallTime);
    $("#coverRemark").val(jsonData.coverRemark);
    $("#coverOrgName").val(jsonData.coverOrgName);
    $("#coverPhotoImg").attr("src", jsonData.coverPhoto);
    $("#coverPeriod").val(jsonData.coverPeriod);
    $("#coverServiceLife").val(jsonData.coverServiceLife);
    $.getMainOrgNameAndId(gUserLoginResult.orgId);
    orgDataFlag == 0 ?
        $("#coverMainOrgId").val(jsonData.coverMainOrgId) :
        $("#coverMainOrgId").val(gUserLoginResult.orgId);
    $("#coverShape").val(jsonData.coverShape);
    $("#coverMaterial").val(jsonData.coverMaterial);
    $("#coverSize").val(jsonData.coverSize);
    $("#coverId").val(jsonData.coverId);
    $("#coverCreatorName").val(jsonData.coverCreatorName);
    $("#coverCreatorId").val(jsonData.coverCreatorId);
    $("#coverModifierId").val(gUserLoginResult.userId);
    $("#coverOrgId").val(jsonData.coverOrgId);
    $("#coverPhoto").val(jsonData.coverPhoto);
    $("#coverModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$('#coverForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        projectNumber: {
            validators: {
                stringLength: {max: 20, message: '项目编号长度不超过20'}
            }
        },
        coordinate: {
            validators: {
                notEmpty: {message: '坐标不能为空'},
                stringLength: {max: 40, message: '坐标长度不超过40'}
            }
        },
        coverRoadName: {
            validators: {
                notEmpty: {message: '路名不能为空'},
                stringLength: {max: 20, message: '路名长度不超过20'}
            }
        },
        coverStartRoad: {
            validators: {
                notEmpty: {message: '起始路口不能为空'},
                stringLength: {max: 20, message: '路名长度不超过20'}
            }
        },
        coverEndRoad: {
            validators: {
                notEmpty: {message: '结束路口不能为空'},
                stringLength: {max: 20, message: '路名长度不超过20'}
            }
        },
        coverBrand: {
            validators: {
                stringLength: {max: 20, message: '品牌长度不超过20'}
            }
        },
        coverInstallOrg: {
            validators: {
                stringLength: {max: 50, message: '安装公司长度不超过50'}
            }
        },
        coverInstallTime: {
            validators: {
                stringLength: {max: 50, message: '安装日期长度不超过50'}
            }
        },
        coverRemark: {
            validators: {
                stringLength: {max: 200, message: '说明备注长度不超过200'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var coordinate = $("#coordinate").val().split(",");
    $("#coverProvince").val($("#province").find("option:selected").text());
    $("#coverCity").val($("#city").find("option:selected").text());
    $("#coverArea").val($("#area").find("option:selected").text());
    $("#coverLongitude").val(coordinate[0]);
    $("#coverLatitude").val(coordinate[1]);
    $("#coverRegionId").val($("#area").val());

    var $form = $(e.target);
    var url;
    var formData = $form.serialize();
    if (coverFlag == 0)
        url = "../rds_CoverManage/addCover";
    else
        url = "../rds_CoverManage/updateCover";
    $.ajax({
        url: url,
        type: 'post',
        data: formData,
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    $.alert("数据操作成功", 1);
                    gMainDT.ajax.reload(null, false);
                } else {
                    $.alert("数据操作失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
    $.clearModal($("#coverForm"), $("#coverModal"));
});

$("#coverInstallTime").blur(function () {
    $("#coverInstallTime").val() == "" ? $("#coverInstallTime").val(date) : null;
});

$.showDeleteCover = function (coverId) {
    var count = 1;
    if (coverId == 0) {
        count = $("input:checkbox[id^='checkbox']:checked").length;
        if (count == 0) {
            $.alert("请选择要删除的数据", 2);
            return;
        } else {
            coverId = "";
            $("input:checkbox[id^='checkbox']:checked").each(function () {
                coverId += $(this).val() + ",";
            });
            coverId = coverId.substring(0, coverId.length - 1);
        }
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该' + count + '条数据吗?</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: '../rds_CoverManage/deleteCover',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "coverIds": coverId
                    },
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                $.alert("数据删除成功", 1);
                                gMainDT.ajax.reload(null, false);
                            } else {
                                $.alert("数据删除失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function () {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
};
